//
//  OrderListViewController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/8/2.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit
import MJRefresh
import DZNEmptyDataSet

class OrderListViewController: BaseViewController {
    
    var dataArray = [OrderListModel]()
    
    @IBOutlet weak var topView: UIView!
    @IBOutlet weak var tableView: UITableView!
    var viewLine:UIView!
    
    var lastSeleBtn:UIButton!
    
    var state = 0  //状态 0待支付  2待收货 3已完成 4已取消
    var page = 1
    
    override func viewDidLoad() {
        super.viewDidLoad()
 
        // Do any additional setup after loading the view.
        self.title = "我的订单"
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 210
        
        let header = UIView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: 5))
        header.backgroundColor = UIColor.backgroundColor
        self.tableView.tableHeaderView = header
        
        // 37 1.5
        self.viewLine = UIView.init(frame: CGRect.init(x: 0, y: 45-1.5, width: 37, height: 1.5))
        self.viewLine.backgroundColor = UIColor.init(hexColor: "#f7c201")
        self.viewLine.centerX = (UIScreen.ScreenWidth/4)/2
        self.topView.addSubview(self.viewLine)
        
        self.tableView.emptyDataSetDelegate = self
        self.tableView.emptyDataSetSource = self
        
        self.tableView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: { [weak self] in
            self?.page = 1
            self?.getOrderList()
        })
        
        self.tableView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: { [weak self] in
            self?.page = (self?.page)! + 1
            self?.getOrderList()
        })
        
        let btn = topView.viewWithTag(1001) as! UIButton
        self.lastSeleBtn = btn
        
        PKhud.show()
        self.getOrderList()
        
        NotificationCenter.default.addObserver(self, selector: #selector(getOrderList), name: NSNotification.Name(rawValue: "updateList"), object: nil)
        
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "updateList"), object: nil)
    }
    
    @objc func getOrderList(){
        HttpRequest.requestData(.post, URLString: Api.orderMy.rawValue, parameters: ["state":self.state,"pageNum":self.page,"pageSize":10]) { (result) in
            PKhud.hiden()
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            if result["msg"] as! String == "success"{
                if let array = [OrderListModel].deserialize(from: result["data"] as? [Any]) as? [OrderListModel] {
                    if self.page == 1 {
                        self.dataArray = array
                    }else {
                        self.dataArray = self.dataArray + array
                    }
                    if array.count < 10 {
                        self.tableView.mj_footer.endRefreshingWithNoMoreData()
                    }
                    self.tableView.reloadData()
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: 待支付
    @IBAction func waitPayMethod(_ sender: UIButton) {
        guard sender != self.lastSeleBtn else {
            return
        }
        sender.isSelected = true
        self.lastSeleBtn.isSelected = false
        self.lastSeleBtn = sender
        self.state = 0
        UIView.animate(withDuration: 0.5) {
            self.viewLine.centerX = (UIScreen.ScreenWidth/4)/2
        }
        self.tableView.mj_header.beginRefreshing()
    }
    
    
    // MARK:待收货
    @IBAction func waitDeliveryMethod(_ sender: UIButton) {
        guard sender != self.lastSeleBtn else {
            return
        }
        sender.isSelected = true
        self.lastSeleBtn.isSelected = false
        self.lastSeleBtn = sender
        self.state = 2
        UIView.animate(withDuration: 0.5) {
            self.viewLine.centerX = UIScreen.ScreenWidth/4*2 - (UIScreen.ScreenWidth/4)/2
        }
        self.tableView.mj_header.beginRefreshing()
    }
    
    // MARK:已完成
    @IBAction func doneMethod(_ sender: UIButton) {
        guard sender != self.lastSeleBtn else {
            return
        }
        sender.isSelected = true
        self.lastSeleBtn.isSelected = false
        self.lastSeleBtn = sender
        self.state = 3
        UIView.animate(withDuration: 0.5) {
            self.viewLine.centerX = UIScreen.ScreenWidth/4*3 - (UIScreen.ScreenWidth/4)/2
        }
        self.tableView.mj_header.beginRefreshing()
    }
    
    
    // MARK:以取消
    @IBAction func canceled(_ sender: UIButton) {
        guard sender != self.lastSeleBtn else {
            return
        }
        sender.isSelected = true
        self.lastSeleBtn.isSelected = false
        self.lastSeleBtn = sender
        self.state = 4
        UIView.animate(withDuration: 0.5) {
            self.viewLine.centerX = UIScreen.ScreenWidth/4*4 - (UIScreen.ScreenWidth/4)/2
        }
        self.tableView.mj_header.beginRefreshing()
    }

}

extension OrderListViewController:UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "OrderListTableViewCell") as! OrderListTableViewCell
        
        cell.reload(withModel: self.dataArray[indexPath.row])
        
        cell.backClosure = { [weak self] in
            let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "ShoppingCartViewController") as! ShoppingCartViewController
            ctrl.orderId = (self?.dataArray[indexPath.row].id)!
            self?.navigationController?.pushViewController(ctrl, animated: true)
        }
        
        cell.confirmPay = { [weak self] in
            var model = ConfirmOrderModel()
            model.money = (self?.dataArray[indexPath.row].money)!
            
            var arr = [OrdersModel]()
            var orderMdl =  OrdersModel()
            orderMdl.number = (self?.dataArray[indexPath.row].number)!
            orderMdl.money = (self?.dataArray[indexPath.row].money)!
            orderMdl.id = (self?.dataArray[indexPath.row].id)!
            arr.append(orderMdl)
            model.orders = arr
            
            let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "SelePayViewController") as! SelePayViewController
            ctrl.model = model
            self?.navigationController?.pushViewController(ctrl, animated: true)
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "OrderDetailViewController") as! OrderDetailViewController
        ctrl.orderModel = self.dataArray[indexPath.row]
        self.navigationController?.pushViewController(ctrl, animated: true)
    }
    
}


extension OrderListViewController:DZNEmptyDataSetSource,DZNEmptyDataSetDelegate {
    
    func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
        let str = "老板,您还没有下单哦~"
        let attribute = NSMutableAttributedString.init(string: str)
        attribute.addAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 14),
                                 NSAttributedStringKey.foregroundColor:UIColor.init(hexColor: "666666")], range: NSRange.init(location: 0, length: str.count))
        
        return attribute
    }
    
    func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
        return UIImage.init(named: "img_Defaultheadimage")
    }
}



















